package com.eversec.view.panel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import com.eversec.model.exception.FileCheckExceptionBean;
import com.eversec.model.filetable.FileCheckTableModel;
import com.eversec.model.filetable.FileCheckTableRender;
import com.eversec.util.command.CharacterEnding;
import com.eversec.util.resource.ResourceUtils;
import com.eversec.util.xml.ValidateXML;

/**
 * 文件校对panel
 * 
 * @author lilizhao
 * 
 */
public class FileCheckPanel extends JPanel {

	private static final long serialVersionUID = 7022575764379298922L;

	// north panel组件
	private JLabel catalogLabel;
	private JTextField catalogfField;
	private JButton catalogBroswerButton;

	// center panel组件
	private JTable fileCheckTable;

	// sourth panel组件
	private JButton fileCheckButton;
	private JButton clearButton;

	public FileCheckPanel() {
		initComponents();
		initListener();
	}

	/**
	 * 初始化组件
	 */
	private void initComponents() {
		setLayout(new BorderLayout());
		setBackground(new Color(252, 252, 252));

		JPanel northPanel = initNorthPanel();
		JPanel centerPanel = initCenterPanel();
		JPanel sourthPanel = initSourthPanel();

		add(northPanel, BorderLayout.NORTH);
		add(centerPanel, BorderLayout.CENTER);
		add(sourthPanel, BorderLayout.SOUTH);
	}

	/**
	 * 初始化north panel
	 * 
	 * @return
	 */
	private JPanel initNorthPanel() {
		JPanel northPanel = new JPanel();
		northPanel.setLayout(new GridBagLayout());
		northPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
				BorderFactory.createEtchedBorder()));
		northPanel.setOpaque(false);

		catalogLabel = new JLabel("目录：");
		catalogfField = new JTextField();
		catalogfField.setEditable(false);
		catalogfField.setEnabled(false);
		catalogfField.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		catalogBroswerButton = new JButton("浏览");

		northPanel.add(catalogLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, //
				GridBagConstraints.WEST, GridBagConstraints.NONE, //
				new Insets(5, 5, 5, 0), 0, 0));
		northPanel.add(catalogfField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, //
				GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, //
				new Insets(5, 0, 5, 0), 0, 0));
		northPanel.add(catalogBroswerButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,//
				GridBagConstraints.WEST, GridBagConstraints.NONE, //
				new Insets(5, 0, 5, 0), 0, 0));

		return northPanel;
	}

	/**
	 * 初始化center panel
	 * 
	 * @return
	 */
	private JPanel initCenterPanel() {
		JPanel centerPanel = new JPanel();
		centerPanel.setLayout(new BorderLayout());

		String[] headers = { "文件名", "校对类型", "校对结果", "xsd校对信息", "逻辑校对信息" };

		fileCheckTable = new JTable(new FileCheckTableModel(null, headers));
		fileCheckTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		fileCheckTable.setShowGrid(true);
		fileCheckTable.setBackground(new Color(200, 200, 200));

		// 设置数据向右对齐
		FileCheckTableRender tableCellRenderer = new FileCheckTableRender();
		tableCellRenderer.setHorizontalAlignment(JLabel.RIGHT);
		fileCheckTable.setDefaultRenderer(Object.class, tableCellRenderer);

		// 设置表头居中对齐
		((DefaultTableCellRenderer) fileCheckTable.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);

		JScrollPane fileCheckScrollPane = new JScrollPane(fileCheckTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		fileCheckScrollPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
				BorderFactory.createEtchedBorder()));

		centerPanel.add(fileCheckScrollPane, BorderLayout.CENTER);
		centerPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
				BorderFactory.createEtchedBorder()));
		centerPanel.setOpaque(false);
		return centerPanel;
	}

	/**
	 * 初始化sourth panel
	 * 
	 * @return
	 */
	private JPanel initSourthPanel() {
		JPanel sourthPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

		Box mainBox = Box.createHorizontalBox();

		fileCheckButton = new JButton("校对");

		clearButton = new JButton("清空");

		mainBox.add(fileCheckButton);
		mainBox.add(clearButton);

		sourthPanel.add(mainBox);

		sourthPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
				BorderFactory.createEtchedBorder()));
		sourthPanel.setOpaque(false);
		return sourthPanel;
	}

	/**
	 * 添加监听
	 */
	private void initListener() {
		catalogBroswerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				fileChooser.setMultiSelectionEnabled(false);
				int preesButton = fileChooser.showOpenDialog(FileCheckPanel.this);
				if (preesButton == JFileChooser.APPROVE_OPTION) {
					File selectedFile = fileChooser.getSelectedFile();
					catalogfField.setText(fileChooser.getSelectedFile().getAbsolutePath());

					File[] fileFilters = FileFilterUtils.filter(new SuffixFileFilter(".src"), selectedFile.listFiles());
					FileCheckTableModel model = (FileCheckTableModel) fileCheckTable.getModel();

					model.setRowCount(0);
					for (File file : fileFilters) {
						model.addRow(new Object[] { file.getName(), null, null, null });
					}
					fileCheckTable.invalidate();
				}
			}
		});
		fileCheckButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int selectedRowCount = fileCheckTable.getSelectedRowCount();
				if (selectedRowCount == 0) {
					JOptionPane.showMessageDialog(FileCheckPanel.this, "请选择需要校对的文件", "", JOptionPane.INFORMATION_MESSAGE);
				} else {
					int[] selectedRows = fileCheckTable.getSelectedRows();
					for (int i : selectedRows) {
						FileCheckTableModel model = (FileCheckTableModel) fileCheckTable.getModel();
						String fileName = model.getValueAt(i, 0).toString();

						try {
							// 获得xml路径和xsd路径
							String xmlPath = catalogfField.getText().trim() + "/" + fileName;
							String rootEleName = getXmlRootElement(xmlPath);
							String checkType = ResourceUtils.propMaps.get(rootEleName).substring(0, 2);

							String xsdPath = System.getProperty("user.dir") + "/config/xsd/" + checkType + "/filecheck.xsd";

							// 处理校对类型，根据XML的根元素识别校对类型，设置表列 (i, 1)为校对类型
							model.setValueAt(ResourceUtils.propMaps.get(rootEleName), i, 1);

							FileCheckExceptionBean validateXmlBasedOnXsd = ValidateXML.validateXmlBasedOnXsd(xsdPath, xmlPath);
							FileCheckExceptionBean validateXmlBasedOnLogic = ValidateXML.validateXmlBasedOnLogic(checkType, xmlPath);

							// 处理xsd校对结果列及逻辑校对结果列数据 (i, 3)与(i, 4)
							// 如果不抛错，则设置为格式良好
							// 如果抛错，则在异常中获取错误信息
							model.setValueAt(validateXmlBasedOnXsd.getFlag() && validateXmlBasedOnLogic.getFlag(), i, 2);
							model.setValueAt(validateXmlBasedOnXsd, i, 3);
							model.setValueAt(validateXmlBasedOnLogic, i, 4);
						} catch (Exception e) {
							model.setValueAt(Boolean.FALSE, i, 2);
							model.setValueAt(e.getMessage(), i, 3);
							model.setValueAt(e.getMessage(), i, 4);
						}
					}
				}
			}

			/**
			 * 根据传入的xml路径获得文件的根元素
			 * 
			 * @param xmlPath
			 * @return
			 * @throws DocumentException
			 * @throws FileNotFoundException 
			 * @throws UnsupportedEncodingException 
			 */
			private String getXmlRootElement(String xmlPath) throws DocumentException, UnsupportedEncodingException, FileNotFoundException {
				SAXReader reader = new SAXReader();
				
				File xmlFile = new File(xmlPath);
				String encoding = CharacterEnding.getFileCharacterEnding(xmlFile);
				reader.setEncoding(encoding);
				
				Document document = reader.read(xmlFile);
				String rootEleName = document.getRootElement().getName();
				return rootEleName;
			}

		});
		clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				catalogfField.setText("");
				FileCheckTableModel model = (FileCheckTableModel) fileCheckTable.getModel();
				model.setRowCount(0);
				;
			}
		});
	}

}
